package com.fyzk.activity.lottery.jc.football.newJz.data;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.fyzk.base.BaseActivity;
import com.fyzk.view.TopTitleView;
import com.fyzk.view.myview.MyWebView;
import com.tyjc.lottery.R;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;

import http.DataUtil.text.TextUtil;

/**
 * Created by gmj on 20/12/27.
 * 比分直播详情
 */
public class NewScoreDetailActivity extends BaseActivity {

    private TopTitleView mTopTitleView;
    private MyWebView mWebView;

    protected boolean isFootball = true;
    protected String matchNum = "20160511001";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_new_score_detail);

        isFootball = getIntent().getBooleanExtra("isFootball", true);
        matchNum = getIntent().getStringExtra("matchNum");

        initView();

        fixUrl(null);
    }

    private void initView() {

        mTopTitleView = findViewById(R.id.mTopTitleView);
        mTopTitleView.setCenterText(getTopTitle());
        mTopTitleView.setRightImg(R.drawable.hm_refresh_click);
        mTopTitleView.setOnTitleClickListener(this);

        mWebView = findViewById(R.id.mWebView);

        initWebView();
    }

    private void initWebView() {
        WebSettings settings = mWebView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        settings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        settings.setBlockNetworkImage(false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        mWebView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url == null)
                    return false;
                try {
                    if (!url.startsWith("http://") && !url.startsWith("https://")) {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        startActivity(intent);
                        return true;
                    }
                } catch (Exception e) {//防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)
                    return true;//没有安装该app时，返回true，表示拦截自定义链接，但不跳转，避免弹出上面的错误页面
                }
                //返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
//                view.loadUrl(url);
                fixUrl(url);
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }
        });
    }

    String url = "";

    private void fixUrl(String baseUrl) {
        if (TextUtil.isEmpty(baseUrl)) {
            if (isFootball) {
//                url = "http://m.fox008.com/analysis/tips/" + matchNum + ".html";
                url = String.format("http://m.fox008.com/analysis/tips/%s.html",matchNum);
            } else {
//                url = "https://data.fox008.com//basketball/lqHistory?matchKey=" + matchNum + "&cooph5=";
                url = String.format("https://data.fox008.com//basketball/lqHistory?matchKey=%s&cooph5=",matchNum);
            }
        } else {
            url = baseUrl;
        }

        new Thread(() -> {
            try {
                Document document = Jsoup.connect(url).get();
                //隐藏标题
                Element header = document.select("header").first();
                if (header != null)
                    header.attr("style", "display:none");
//                if (isFootball) {
                    //隐藏来自某某的一线情报
                    Elements qbwzss = document.getElementsByClass("qbwzss");
                    if (null != qbwzss){
                        for (Element element : qbwzss) {
                            if (null != element)
                                element.attr("style", "display:none");
                        }
                    }
                    //隐藏底部赞赏
                    Element ds_btnr = document.getElementsByClass("ds_btnr").first();
                    if (ds_btnr != null)
                        ds_btnr.attr("style", "display:none");
//                } else {
                    //隐藏a标签广告图
                    Elements as = document.select("a[href]");
                    if (null != as) {
                        for (Element element : as) {
                            //https://m.fox008.com
                            if (null != element && element.attr("abs:href").contains("https://m.fox008.com")) {
                                element.attr("style", "display:none");
                            }
                        }
//                    }

                    Element nodata = document.getElementsByClass("nodata").first();
                    if (nodata != null)
                        nodata.attr("style", "display:none");
                }
                runOnUiThread(() -> loadUrl(url, document.outerHtml()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }

    private void loadUrl(String baseUrl, String outerHtml) {
        mWebView.loadDataWithBaseURL(baseUrl, outerHtml, "text/html", "utf-8", null);
    }

    protected String getTopTitle() {
        return isFootball ? "竞足分析" : "竞篮分析";
    }

    @Override
    public void onRightClick() {
        fixUrl(url);
    }

    @Override
    protected void onDestroy() {
        mWebView.clearCache(true);
        mWebView.removeAllViews();
        mWebView.destroy();
        super.onDestroy();
    }
}
